<?php


namespace App\Service\Cooperative;


use App\Constants\ErrorCode;
use App\Dao\ConfigOtherDao;
use App\Exception\BusinessException;
use App\Model\ConfigOther;
use Hyperf\Di\Annotation\Inject;

class ConfigOtherService extends BaseService
{

    /**
     * @Inject()
     * @var ConfigOtherDao
     */
    protected $configOtherDao;

    /**
     * @return array
     */
    public function index():array
    {
        $where = [];
        $where['cooperative_id'] = $this->user()->cooperative_id;
        $configOthers = $this->configOtherDao->where($where)->get();

        $data = [];

        /** @var ConfigOther $configOther */
        foreach($configOthers as $configOther){
            $data[] = [
                'name' => $configOther->name,
                'value' => $configOther->val
            ];
        }
        return $data;
    }

    /**
     * @param string $name
     * @param array $data
     * @return ConfigOther
     */
    public function save(string $name, array $data): ConfigOther
    {
        /** @var ConfigOther $configOther */
        $configOther = $this->configOtherDao->first([
            'name' => $name,
            'cooperative_id' => $this->user()->cooperative_id
        ]);

        if (!$configOther) {
            throw new BusinessException(ErrorCode::COOPERATIVE_CONFIG_OTHER_NOT_FOUND);
        }

        $configOther->val = $data['value'];
        $configOther->save();
        return $configOther;
    }

}